import React, {Component} from 'react';
import {connect} from 'react-redux';

import * as marketActionCreators from '../../actions/MarketAction';
import * as newsActionCreators from '../../actions/NewsActions';
import colors from "../../styles/colors";
import view from './view';

let timeinterval = null;
let timeintervalArr = [];

class Home extends Component {

  render() {
    return view(this, timeinterval, timeintervalArr);
  }

  componentDidMount() {
    const {getBannerList, getNewsNoticeList} = this.props;
    getBannerList();
    getNewsNoticeList(304, 1, 5);
  }

  topTickerShow(order) {
    const {allTicker} = this.props;
    let tickerShowArr = [];
    for (let i in allTicker) {
      let ticker = allTicker[i];
      if (ticker.order <= order) {
        tickerShowArr.push(ticker)
      }
    }
    return tickerShowArr
  }

  // 根据order取出前10
  bottomTickerList() {
    const {allTicker} = this.props;
    let tenTickerArr = [];
    for (let i in allTicker) {
      allTicker[i].percent = this.changePercent(allTicker[i].close, allTicker[i].open);
      if (allTicker[i].order <= 10) {
        tenTickerArr.push(allTicker[i])
      }
    }
    tenTickerArr.sort((a, b) => {
      return a.order - b.order
    });
    return tenTickerArr;
  }

  // 计算涨跌幅
  changePercent(close, open) {
    let priceSpread = close - open;
    let percentString = '';
    if (priceSpread === 0) {
      percentString = '0.00%';
    } else {
      let percentNumber = priceSpread * 100 / open;
      percentString = (priceSpread < 0 ? '' : '+') + percentNumber.toFixed(2) + '%';
    }
    return percentString;
  }

  // 绿涨红跌
  changeColor(close, open) {
    if (close - open > 0) {
      return colors.riseGreen
    } else if (close - open < 0) {
      return colors.fallRed
    } else {
      return colors.stopGray
    }
  }

}

const mapStateToProps = (state) => {
  return {
    banner: state.news.banner,
    newsNoticeList: state.news.newsNoticeList,
    allTicker: state.market.allTicker
  }
};

const mapDispatchToProps = (dispatch) => {
  return {
    getBannerList() {
      dispatch(newsActionCreators.getBannerList());
    },
    getNewsNoticeList(columnId, page, pageSize) {
      dispatch(newsActionCreators.getNewsNoticeList(columnId, page, pageSize));
    },
    getAllTicker() {
      timeinterval = setInterval(() => dispatch(marketActionCreators.getAllTicker()), 3000);
      timeintervalArr.push(timeinterval);
    }
  }
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);